#include "swegl/profiling.h"

#include <stdio.h>
#include <stdlib.h>

//todo: move it to be globally accesible
namespace
{

uint VSprintf(char *dest, uint size, const char *fmt, va_list args)
{
#ifdef _WIN32
	uint ret = static_cast<uint>(::_vsnprintf_s(dest, size, size - 1, fmt, args));
#else
	uint ret = static_cast<uint>(::vsnprintf(dest, size, fmt, args));
#endif
	dest[size - 1] = '\0';
	if (static_cast<sint>(ret) < 0)
	{
		sweglWarning("VSprintf: destination buffer overflow (%u), truncate result\n", size);
		ret = size - 1;
	}
	else if (ret >= size)
	{
		sweglWarning("VSprintf: destination buffer overflow (%u >= %u), truncate result\n", ret, size);
		ret = size - 1;
	}
	return ret;
}
}

namespace swegl
{
namespace Assert
{

void AssertionFailed(char const *expr, char const *function, char const *file, long line)
{
	sweglWarning("Assertion failed:\n");
	sweglWarning("   expr    : %s\n", expr);
	sweglWarning("   file    : %s\n", file);
	sweglWarning("   line    : %ld\n", line);
	sweglWarning("   function: %s\n", function);

	//while (1) { Sleep(1); }
	exit(0);
}

void AssertionFailed(char const *expr, char const *function, char const *file, long line, const char *fmt, ...)
{
	char msg[4096];
	va_list args;
	va_start(args, fmt);
	VSprintf(msg, sizeof(msg), fmt, args);
	va_end(args);

	sweglWarning("Assertion failed: %s\n", msg);
	sweglWarning("   expr    : %s\n", expr);
	sweglWarning("   file    : %s\n", file);
	sweglWarning("   line    : %ld\n", line);
	sweglWarning("   function: %s\n", function);

	//while (1) { Sleep(1); }
	exit(0);
}

}
}

